package com.per.hjh.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.per.hjh.model.User;
import com.per.other.until.ImageCode;
import com.per.other.until.UserHelper;



/**
 * Servlet Filter implementation class Loginfilter
 */

@Component("loginfilter")
public class Loginfilter implements Filter {
	private String accessList;
	@Autowired
	private ImageCode imageCode;
    /**
     * Default constructor. 
     */
    public Loginfilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here

		// pass the request along the filter chain
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		HttpSession session = request.getSession();
		//获取请求uri
		String uri = request.getRequestURI();
		int beginOffset = uri.indexOf(request.getContextPath()) + request.getContextPath().length();
		int endOffset = uri.indexOf("?");
		String target = endOffset > 0 ? uri.substring(beginOffset, endOffset) : uri.substring(beginOffset);
		String[] list = accessList.split(",");
		User currentUser = UserHelper.getLoginUser(request);
		
		boolean flag = false;
		for (int i = 0; i < list.length; i++) {
			if (list[i].equals(target)) {
				flag = true;
				break;
			}
		}
		if (flag) {
			if("login.do".equals(target)) {
				response.sendRedirect(request.getContextPath()+"/login.do");
				
			} else {
				System.err.println(currentUser+"-----");
				chain.doFilter(request, response);
			}
			
		}else{
			if(currentUser==null){
				response.sendRedirect(request.getContextPath()+"/login.do");
			}else
			chain.doFilter(request, response);}
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
		System.err.println("网站在验证信息");
		accessList = fConfig.getInitParameter("accessList");
		
	}

}
